class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # , :confirmable,
  # :lockable, :timeoutable and             :validatable,
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable,
         :token_authenticatable, :omniauthable, :omniauth_providers => [:google_oauth2]

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me,
                  :name, :latitude, :longitude,
                  :provider, :uid
  # attr_accessible :title, :body

  has_many  :group_users
  has_many :groups, :through => :group_users

  has_many  :requests, :foreign_key => "sender_id"

  has_many  :messages

  def self.from_omniauth(auth)
    if user = User.find_by_email(auth.info.email)
      user.provider = auth.provider
      user.uid = auth.uid
      user
    else
      where("email = ?", auth.info.email).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.email = auth.info.email
      end
    end
  end

  def self.from_mobile(email, token)
    if email.nil? == false && token.nil? == false then
      if user = User.find_by_email(email)
        user.provider = "mobile"
        user
      else
        where("email = ?", email).first_or_create do |user|
          user.provider = "mobile"
          user.email = email
        end
      end
    end
  end

end
